package concurrency

import (
	"cow_golang/shared_mod/logger"
	"sync"
)

// 环形队列实现
type JobQueue struct {
	tasks      []Job      // 任务数组
	mu         sync.Mutex // 队列专用锁
	head       int        // 队列头指针
	tail       int        // 队列尾指针
	count      int        // 当前任务数
	closed     bool       // 关闭标志
	queueSize  int        // 队列容量
	processing int32      // 处理标志 (0: 未处理, 1: 处理中)
}

// 创建工作队列
func NewQueue(size int) *JobQueue {
	q := &JobQueue{
		tasks:     make([]Job, size),
		queueSize: size,
	}
	return q
}

// 加入任务
func (q *JobQueue) Enqueue(job Job) bool {
	q.mu.Lock()
	defer q.mu.Unlock()

	// 判断队列状态和队列是否满了
	if q.closed || q.count == q.queueSize {
		logger.GetInstance().Error("Enqueue queue close or full")
		return false
	}

	q.tasks[q.tail] = job
	q.tail = (q.tail + 1) % q.queueSize
	q.count++
	logger.GetInstance().Debugf("Enqueue queue size： %d dequeued", q.count)
	return true
}

// 获取任务
func (q *JobQueue) Dequeue() (Job, bool) {
	q.mu.Lock()
	defer q.mu.Unlock()

	for q.count <= 0 || q.closed {
		return nil, false
	}

	job := q.tasks[q.head]
	q.head = (q.head + 1) % q.queueSize
	q.count--
	logger.GetInstance().Debugf("Dequeue queue size： %d dequeued", q.count)
	return job, true
}

func (q *JobQueue) Close() {
	q.mu.Lock()
	defer q.mu.Unlock()
	q.closed = true
}

func (q *JobQueue) Len() int {
	q.mu.Lock()
	defer q.mu.Unlock()
	return q.count
}
